package kstech.com.wifitest.activity;

import android.app.AlertDialog;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.utils.EntryXComparator;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import J1939.J1939_Context;
import J1939.J1939_Task;
import J1939.can_Message_ts;
import kstech.com.wifitest.Point;
import kstech.com.wifitest.listener.BatteryListener;
import kstech.com.wifitest.listener.ItemDataListener;
import kstech.com.wifitest.R;
import kstech.com.wifitest.communication.CommandSender;
import kstech.com.wifitest.communication.CommunicationWorker;
import kstech.com.wifitest.utils.AppContext;
import kstech.com.wifitest.utils.DateUtil;
import kstech.com.wifitest.utils.Globals;
import kstech.com.wifitest.utils.TextFile;

public class MainActivity extends AppCompatActivity implements View.OnClickListener,ItemDataListener,BatteryListener{

    //1939相关
    private J1939_Task j1939ProtTask;
    private CommunicationWorker j1939CommTask;
    private int DATA1 = 1;
    private int DATA2 = 2;
    private Button btnStartCheck;
    private Button btnSaveData;
    private Button btnLocalData;
    private Button btnStopData;

    private Button btnSafeComm;
    private LinearLayout llSafeComm;

    private LineChart mChart;
    private LineData data;
    private List<Entry> entries;
    private List<Entry> entries2;
    private LineDataSet dataset;
    private LineDataSet dataset2;
    private int x = 1;
    private int x2 = 1;
    private int count = 0;
    private LinearLayout.LayoutParams params;

    private Button btnNoResponse;
    private LinearLayout llNoResponse;
    private AlertDialog.Builder dialog;
    private AlertDialog alert;
    private ArrayList<Float> localList1;
    private ArrayList<Float> localList2;

    private TextView battery;

    public Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:
                    float dataf = msg.getData().getFloat("DATA1");
                    entries.add(new Entry(x++,dataf));
                    mChart.postInvalidate();
                    if(mChart.getLineData().getDataSetCount() > 0){
                        LineDataSet tempdata = (LineDataSet) mChart.getData().getDataSetByIndex(0);
                        tempdata.setValues(entries);
                        mChart.getData().notifyDataChanged();
                        mChart.notifyDataSetChanged();
                    }
                    break;
                case 2:
                    float data2 = msg.getData().getFloat("DATA2");
                    entries2.add(new Entry(x2++,data2));
                    mChart.postInvalidate();
                    if(mChart.getLineData().getDataSetCount() > 1){
                        LineDataSet tempdata = (LineDataSet) mChart.getData().getDataSetByIndex(1);
                        tempdata.setValues(entries2);
                        mChart.getData().notifyDataChanged();
                        mChart.notifyDataSetChanged();
                    }

                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        AppContext.context = this;
        J1939Init();

        initView();

        chartinit();

        AppContext.getModelFile().getDataSetVO().getDSItem("电量").batteryListener = this;

    }


    //初始化View
    private void initView(){
        btnStartCheck = (Button) findViewById(R.id.btn_start_check);
        btnNoResponse = (Button) findViewById(R.id.btn_no_response);
        btnSaveData = (Button) findViewById(R.id.btn_data_save);
        btnStopData = (Button) findViewById(R.id.btn_local_stop);
        btnLocalData = (Button) findViewById(R.id.btn_local_show);
        btnSafeComm = (Button) findViewById(R.id.btn_safe_comm);
        llSafeComm = (LinearLayout) findViewById(R.id.ll_safe_comm);
        llNoResponse = (LinearLayout) findViewById(R.id.ll_no_response);
        battery = (TextView) findViewById(R.id.tv_battery);


        mChart = (LineChart) findViewById(R.id.chart_wifi);

        btnStartCheck.setOnClickListener(this);
        btnSafeComm.setOnClickListener(this);
        btnNoResponse.setOnClickListener(this);
        btnSaveData.setOnClickListener(this);
        btnLocalData.setOnClickListener(this);
        btnStopData.setOnClickListener(this);

        params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        dialog = new AlertDialog.Builder(this);
    }

    public void chartinit(){
        //设置是否可以触摸，如为false，则不能拖动，缩放等
        mChart.setTouchEnabled(true);
        //设置是否可以拖拽，缩放
        mChart.setDragEnabled(true);
        mChart.setScaleEnabled(true);
        //设置是否能扩大扩小
        mChart.setPinchZoom(true);

        mChart.setDrawGridBackground(false);
        XAxis xAx = mChart.getXAxis();
        xAx.setAxisMinimum(0);
        xAx.setGridColor(R.color.trans);

        mChart.getAxisLeft().setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                BigDecimal v = new BigDecimal(value);
                v = v.setScale(2,BigDecimal.ROUND_HALF_UP);
                float dataf = v.floatValue();
                return dataf+" MA";
            }
        });

        //设置x轴位置
        mChart.getXAxis().setPosition(XAxis.XAxisPosition.BOTTOM);

        data = new LineData();
        entries = new ArrayList<>();
        entries2 = new ArrayList<>();
        entries.add(new Entry(0,0));
        entries2.add(new Entry(0,0));
        dataset = new LineDataSet(entries,"channel1");
        dataset2 = new LineDataSet(entries2,"channel2");
        dataset.setColor(Color.RED);
        dataset2.setColor(Color.argb(255,139,71,38));
        dataset.setMode(LineDataSet.Mode.CUBIC_BEZIER);
        dataset2.setMode(LineDataSet.Mode.CUBIC_BEZIER);
        // 显示坐标点的小圆点
        dataset.setDrawCircles(false);
        dataset2.setDrawCircles(false);
        // 不显示坐标点的数据
        dataset.setDrawValues(false);
        dataset2.setDrawValues(false);
        data.addDataSet(dataset);
        data.addDataSet(dataset2);
        mChart.setData(data);
    }

    //初始化 1939相关线程
    private void J1939Init() {
        AppContext.initResource();
        try {
            AppContext.loadDeviceModelFile("0004","00001001");
        } catch (Exception e) {
            Log.e("MainActivity", e.toString());
            e.printStackTrace();
        }
        j1939ProtTask = new J1939_Task();
        j1939ProtTask.Init(this);
        // 启动协议任务
        j1939ProtTask.start();

        // 启动通讯任务
        j1939CommTask = new CommunicationWorker("192.168.1.178", 4001);
        Log.e("hahah","j1939CommTask start");
        j1939CommTask.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        j1939ProtTask.setStop(true);
        j1939ProtTask = null;
        j1939CommTask.setStop(true);
        j1939CommTask = null;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_start_check:
                CommandSender.sendStartCheckCommand("1",1);
                //判断当前正在显示本地数据则清空图表，否则就直接发送命令
                if (mChart.getLineData().getDataSetByIndex(0) != null){
                    if("local_channel1".equals(mChart.getLineData().getDataSetByIndex(0).getLabel())){
                        //清空表数据
                        mChart.getLineData().clearValues();
                        if (entries != null || entries.size()==0) entries.clear();
                        if (entries2 != null || entries2.size()==0) entries2.clear();
                        x = 1; x2 = 1;
                        chartinit();
                        CommandSender.sendStartCheckCommand("50",1);
                    }else {
                        CommandSender.sendStartCheckCommand("50",1);
                    }
                }else {
                    chartinit();
                    CommandSender.sendStartCheckCommand("50",1);
                }


                break;
            case R.id.btn_safe_comm:
                CommandSender.sendStartCheckCommand("51",1);
                break;
            case R.id.btn_no_response:
                Globals.progress = 0;
                CommandSender.sendStartCheckCommand("52",1);
                break;
            case R.id.btn_local_stop:
                Globals.progress = 0;
                can_Message_ts canmsg = new can_Message_ts();
                canmsg.id_u32 = 0x18ff8035;
                canmsg.format_u8 = 1;
                canmsg.numBytes_u8 = 8;
                canmsg.data_au8 = new byte[]{50,1,2,0,0,0,0,0};
                J1939_Context.j1939_CommCfg.can_TxFIFO.add(canmsg);
                //CommandSender.sendStopCheckCommand("50",1);
                break;
            case R.id.btn_data_save:
                count = 0;

                final Timer timer = new Timer();
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        count ++;
                        if(count>7){
                            alert.dismiss();
                            timer.cancel();
                            Toast.makeText(getApplicationContext(),"保存失败 wu wu wu",Toast.LENGTH_SHORT).show();
                        }
                    }
                },0,1000);

                View view = View.inflate(this,R.layout.dialog_write,null);

                alert = dialog.setView(view).setCancelable(false)
                        .create();
                alert.show();
                new Thread(){
                    @Override
                    public void run() {
                        writeData(dataset.getValues(),dataset2.getValues());
                        timer.cancel();
                        alert.dismiss();
                    }
                }.start();

                break;
            case R.id.btn_local_show:

                //清空表数据
                mChart.getLineData().clearValues();
                if (entries != null) entries.clear();
                if (entries2 != null) entries2.clear();

                //从本地读取表数据添加数据
                localList1 = TextFile.read("/storage/sdcard1/linechart.txt","$s1$");
                localList2 = TextFile.read("/storage/sdcard1/linechart.txt","$s2$");

                x = 1; x2 = 1;

                if(localList1 == null || localList2 == null || localList1.size() == 0  || localList2.size() == 0) {
                    Toast.makeText(this, "本地未检测到数据", Toast.LENGTH_SHORT).show();
                    return;
                }

                for (Float aFloat : localList1) {
                    entries.add(new Entry(x++,aFloat));
                }
                for (Float aFloat : localList2) {
                    entries2.add(new Entry(x2++,aFloat));
                }

                //对于entry集合进行数据调整 是的X值为递增
                Collections.sort(entries, new EntryXComparator());
                Collections.sort(entries2, new EntryXComparator());

                //曲线格式调整
                LineData tempData = new LineData();
                LineDataSet temdataset = new LineDataSet(entries, "local_channel1");
                LineDataSet temdataset2 = new LineDataSet(entries2, "local_channel2");
                temdataset.setColor(Color.argb(255,255,140,0));
                temdataset2.setColor(Color.argb(255,153,50,204));
                temdataset.setMode(LineDataSet.Mode.CUBIC_BEZIER);
                temdataset2.setMode(LineDataSet.Mode.CUBIC_BEZIER);
                // 显示坐标点的小圆点
                temdataset.setDrawCircles(true);
                temdataset2.setDrawCircles(true);
                // 不显示坐标点的数据
                temdataset.setDrawValues(false);
                temdataset2.setDrawValues(false);
                tempData.addDataSet(temdataset);
                tempData.addDataSet(temdataset2);
                mChart.setData(tempData);

                mChart.getData().notifyDataChanged();
                mChart.notifyDataSetChanged();
                mChart.invalidate();
                break;
        }
    }

    @Override
    public void onDataChanged(Point fvalue) {

//        float valuef = fvalue/1000f;
//        //float value = 4024.336f;
//        BigDecimal v = new BigDecimal(valuef);
//        v = v.setScale(2,BigDecimal.ROUND_HALF_UP);
//        float dataf = v.floatValue();
//
//        Message msg = Message.obtain();
//        msg.what = DATA1;
//        Bundle b = new Bundle();
//        b.putFloat("DATA1",dataf);
//        msg.setData(b);
//        handler.sendMessage(msg);
    }

    @Override
    public void onData2Changed(Point fvalue) {
//        float valuef = fvalue/1000f;
//        //float value = 4024.336f;
//        BigDecimal v = new BigDecimal(valuef);
//        v = v.setScale(2,BigDecimal.ROUND_HALF_UP);
//        float dataf = v.floatValue();
//
//        Message msg = Message.obtain();
//        msg.what = DATA2;
//        Bundle b = new Bundle();
//        b.putFloat("DATA2",dataf);
//        msg.setData(b);
//        handler.sendMessage(msg);
    }

    @Override
    public void onDataChangeSafeMODE(final String value) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                TextView tv = new TextView(getApplicationContext());
                tv.setTextSize(18);
                tv.setTextColor(Color.BLACK);
                tv.setText(value);
                tv.setGravity(Gravity.CENTER);
                llSafeComm.addView(tv,0,params);
            }
        });

    }

    @Override
    public void onDataNoResponse(final String value, final long remote, final int local) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if(!"err".equals(value)){
                    TextView tv = new TextView(getApplicationContext());
                    tv.setTextSize(18);
                    tv.setTextColor(Color.BLACK);
                    tv.setText("--remote:"+remote+"--    --local:"+local);
                    tv.setGravity(Gravity.CENTER);
                    llNoResponse.addView(tv,0,params);
                }else {

                }

            }
        });
    }
    private synchronized void writeData(List<Entry> values,List<Entry> values2){
        AppContext.storeEntry(values,values2);
        AppContext.write(values, values2,DateUtil.getDateTimeFormat14(new Date()));
    }

    @Override
    public void onBatteryChanged(final float data) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                battery.setText("电量："+data);
            }
        });
    }
}
